package backend

import (
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许所有来源
	},
}

// WebSocketWrapper WebSocket连接包装器
type WebSocketWrapper struct {
	conn  *websocket.Conn
	mutex sync.Mutex
}

// WriteMessage 向WebSocket连接写入消息
func (w *WebSocketWrapper) WriteMessage(message Message) error {
	w.mutex.Lock()
	defer w.mutex.Unlock()

	return w.conn.WriteJSON(message)
}

// Close 关闭WebSocket连接
func (w *WebSocketWrapper) Close() error {
	return w.conn.Close()
}

// UnderlyingConn 返回底层的WebSocket连接
func (w *WebSocketWrapper) UnderlyingConn() *websocket.Conn {
	return w.conn
}

// HandleWebSocket 处理WebSocket连接
func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
	// 升级HTTP连接到WebSocket
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("WebSocket upgrade error: %v", err)
		return
	}

	// 创建包装器
	wrapper := &WebSocketWrapper{conn: conn}
	// 创建客户端
	client := &WebSocketClient{
		conn: wrapper,
	}

	// 添加客户端到管理器
	clientID := generateClientID()
	s.mutex.Lock()
	s.clients[clientID] = client
	s.mutex.Unlock()

	log.Printf("New WebSocket client connected. ID: %s, IsSender: %v", clientID)

}

// generateClientID 生成客户端ID
func generateClientID() string {
	// 简单实现，实际项目中可能需要更复杂的ID生成策略
	return time.Now().Format("20060102150405.000")
}
